package com.zkdcloud.service;

import com.zkdcloud.domain.Admin;
import com.zkdcloud.domain.Business;
import com.zkdcloud.repository.AdminDao;
import com.zkdcloud.util.Md5Util;
import com.zkdcloud.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 管理员登录
 *
 * @author zk123
 * @version 2018/4/30
 */
@Service
public class AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private BusinessService businessService;
    /**
     * 根据用户名和密码登录
     *
     * @param username admin
     * @return yes/no
     */
    public Admin checkLogin(String username,String password){
        password = Md5Util.encoding(password);
        List<Admin> resultList = adminDao.findByUserNameAndPassword(username,password);
        return resultList == null || resultList.isEmpty() ? null : resultList.get(0);
    }

    /**
     * 直接添加admin
     *
     * @param admin admin
     */
    public void addAdmin(Admin admin){
        if(StringUtils.isEmpty(admin.getId())){
            admin.setId(RandomUtil.getUUID());
        }
        if(StringUtils.isEmpty(admin.getRealName())){
            admin.setRealName("");
        }
        if(StringUtils.isEmpty(admin.getIdentityNum())){
            admin.setIdentityNum("");
        }
        if(StringUtils.isEmpty(admin.getGender())){
            admin.setIdentityNum("other");
        }
        if(StringUtils.isEmpty(admin.getEmail())){
            admin.setIdentityNum("");
        }
        if(StringUtils.isEmpty(admin.getPhone())){
            admin.setPhone("");
        }
        if(StringUtils.isEmpty(admin.getStatus())){
            admin.setStatus("active");
        }

        admin.setCreateTime(System.currentTimeMillis());
        admin.setId(RandomUtil.getUUID());

        //构建business
        Business business = new Business();
        business.setName(admin.getUserName() + "的店铺");
        business.setId(RandomUtil.getUUID());
        businessService.add(business);

        admin.setBusinessId(business.getId());
        adminDao.addAdmin(admin);
    }

    /**
     * 添加admin 经过密码md5
     *
     * @param admin admin
     */
    public void addAdminWithEncPwd(Admin admin){
        admin.setPassword(Md5Util.encoding(admin.getPassword()));
        addAdmin(admin);
    }

    /**
     * 根据用户名获取admin
     *
     * @param username username
     * @return List<Admin></>
     */
    public List<Admin> getByUserName(String username){
        return adminDao.findByUsername(username);
    }
}
